package com.components.base.action

import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import com.components.base.titlebar.OnTitleBarListener
import com.components.base.titlebar.TitleBar

/**标题栏意图*/
interface TitleBarAction : OnTitleBarListener {
    fun titleBar(): TitleBar?

    /**
     * 左项被点击
     *
     * @param v     被点击的左项View
     */
    override fun onLeftClick(v: View) {}

    /**
     * 标题被点击
     *
     * @param v     被点击的标题View
     */
   override fun onTitleClick(v: View) {}

    /**
     * 右项被点击
     *
     * @param v     被点击的右项View
     */
    override fun onRightClick(v: View) {}

    /**
     * 设置标题栏的标题
     */
    fun setTitle(@StringRes id: Int) {
        titleBar()?.let {
            setTitle(it.resources.getString(id))
        }
    }

    /**
     * 设置标题栏的标题
     */
    fun setTitle(title: CharSequence) {
        titleBar()?.setTitle(title)
    }

    /**
     * 设置标题栏的左标题
     */
    fun setLeftTitle(id: Int) {
        titleBar()?.setLeftTitle(id)
    }

    fun setLeftTitle(text: CharSequence) {
        titleBar()?.setLeftTitle(text)
    }

    fun getLeftTitle(): CharSequence {
        titleBar()?.let {
            return it.getLeftTitle()
        }
        return ""
    }

    /**
     * 设置标题栏的右标题
     */
    fun setRightTitle(id: Int) {
        titleBar()?.setRightTitle(id)
    }

    fun setRightTitle(text: CharSequence) {
        titleBar()?.setRightTitle(text)
    }

    fun getRightTitle(): CharSequence {
        titleBar()?.let {
            return it.getRightTitle()
        }
        return ""
    }

    /**
     * 设置标题栏的左图标
     */
    fun setLeftIcon(id: Int) {
        titleBar()?.setLeftIcon(id)
    }

    fun setLeftIcon(drawable: Drawable) {
        titleBar()?.setLeftIcon(drawable)
    }

    fun getLeftIcon(): Drawable? {
        titleBar()?.let { return it.getLeftIcon() }
        return null
    }

    /**
     * 设置标题栏的右图标
     */
    fun setRightIcon(id: Int) {
        titleBar()?.setRightIcon(id)
    }

    fun setRightIcon(drawable: Drawable) {
        titleBar()?.setRightIcon(drawable)
    }

    fun getRightIcon(): Drawable? {
        titleBar()?.let {
            return it.getRightIcon()
        }
        return null
    }

    /**
     * 递归获取 ViewGroup 中的 TitleBar 对象
     */
    fun obtainTitleBar(group: ViewGroup): TitleBar? {
        for (i in 0 until group.childCount) {
            val view = group.getChildAt(i)
            if (view is TitleBar) {
                return view as TitleBar
            } else if (view is ViewGroup) {
                val titleBar: TitleBar? = obtainTitleBar(view)
                if (titleBar != null) {
                    return titleBar
                }
            }
        }
        return null
    }
}